package com.itljm.cxrMarket.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itljm.cxrMarket.common.PageResult;
import com.itljm.cxrMarket.common.Result;
import com.itljm.cxrMarket.common.StatusCode;
import com.itljm.cxrMarket.entity.Categories;
import com.itljm.cxrMarket.entity.LoginUser;
import com.itljm.cxrMarket.entity.Products;
import com.itljm.cxrMarket.entity.dto.CategoryProductsDTO;
import com.itljm.cxrMarket.service.CategoriesService;
import com.itljm.cxrMarket.service.MerchantsService;
import com.itljm.cxrMarket.service.ProductsService;
import com.itljm.cxrMarket.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ljm
 * @date 2024/12/12 17:07
 */
@RestController
@RequestMapping("/product")
@CrossOrigin
public class ProductController {
    @Autowired
    private ProductsService productsService;
    @Autowired
    private CategoriesService categoriesService;
    @Autowired
    private MerchantsService merchantsService;

    // 查询商品列表,分页
    @RequestMapping("/info")
    public PageResult<Products> selectPageInfo(Integer page, Integer limit,
                                               String productName,String categoryName,
                                               String status,String userId) {
        if (page == null) {
            page = 0;
        }
        if (limit == null) {
            limit = 15;
        }
        Page<Products> productsPage = new Page<>(page, limit);
        QueryWrapper<Products> wrapper = new QueryWrapper<>();
        wrapper.eq("1",1);

        if (StringUtils.isNotEmpty(productName)) {
            wrapper.like("product_name", productName);
        }
        if (StringUtils.isNotEmpty(categoryName)) {
//            Integer id = categoriesService.selectCategoriesIdByName(categoryName);
            wrapper.eq("p.category_id", Integer.parseInt(categoryName));
        }
        if (StringUtils.isNotEmpty(status)) {
            wrapper.eq("status", status);
        }
        if (StringUtils.isNotEmpty(userId) && !"1".equals(userId)) {
            Integer merchantId = merchantsService.selectMerchantIdByUserId(userId);
            wrapper.eq("p.merchant_id", merchantId);
        }

        List<Products> productsList = productsService.selectProductPage(productsPage, wrapper);
        return new PageResult<>(productsList, productsPage.getTotal());
    }

    // 新增或修改商品
    @RequestMapping("/save")
    public Result saveProduct(@RequestBody Products entity) {
        if (entity.getProductId() == null) {
            // 通过SecurityContextHolder获取当前用户的认证信息
            UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            String userId = loginUser.getUser().getId().toString();
            Integer i = merchantsService.selectMerchantIdByUserId(userId);
            entity.setMerchantId(i);
        }
        boolean b = productsService.saveProduct(entity);
        return b ? Result.ok("操作成功") : Result.fail("操作失败");
    }

    // 根据id查询商品详情
    @RequestMapping("/info/{id}")
    public Result selectProductById(@PathVariable Integer id) {
        Products products = productsService.selectProductById(id);
        if (products == null) {
            return Result.fail("查询失败");
        }
        return Result.ok("查询成功", products);
    }

    // 删除商品
    @DeleteMapping("/delete/{id}")
    public Result deleteProductById(@PathVariable Integer id) {
        boolean b = productsService.deleteProductById(id);
        if (!b) {
            return Result.ok("删除失败");
        }
        return Result.ok("删除成功");
    }

    /**
     * 微信小程序接口
     */
    // 查询商品列表,分页
    @RequestMapping("/getAllProducts")
    public PageResult<Products> wxSelectAllPage(Integer page, Integer limit,
                                               String productName,String categoryName) {
        if (page == null) {
            page = 0;
        }
        if (limit == null) {
            limit = 15;
        }
        Page<Products> productsPage = new Page<>(page, limit);
        QueryWrapper<Products> wrapper = new QueryWrapper<>();
        wrapper.eq("1",1);

        if (StringUtils.isNotEmpty(productName)) {
            wrapper.like("product_name", productName);
        }
        if (StringUtils.isNotEmpty(categoryName)) {
            Integer id = categoriesService.selectCategoriesIdByName(categoryName);
            wrapper.eq("p.category_id", id);
        }
        wrapper.eq("status", 1);// 上架商品

        List<Products> productsList = productsService.selectProductPage(productsPage, wrapper);
        return new PageResult<>(productsList, productsPage.getTotal());
    }

    // 获取指定分类下的产品
    @GetMapping("/getWxCategoryGoods")
    public Result getProductsByCategory(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "15") Integer limit,
            @RequestParam(required = false, defaultValue = "1") Integer categoryId) {

        Page<Products> pageInfo = new Page<>(page, limit);
        QueryWrapper<Products> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", categoryId);
        wrapper.eq("status", 1); // 只查询上架商品

        IPage<Products> result = productsService.page(pageInfo, wrapper);
        return Result.ok(result);
    }

}
